/**
 * 新增本地文件
 * 解析 routerConfig.js 文件
 * 在 routerConfig 中添加数据
 * 重新 routerConfig.js 文件
*/
const fs = window.preload.fs;
import { treeToArray,array_getObjPosition,arrayToTree,array_nodeNum,arr_findItem,getAllChild,array_deleteAllItem } from "../tree.js";
import { createNativeFile } from "./nativeFile.js";

function getProject(){
    return eval("(" + localStorage.getItem('projectConfig') + ")").nowProject;
}

//新增页面
async function formatRouteConfig(params,nowRightClickItem){
    let nowProject = getProject();
    const result = await fs.readFile(`${window.preload.dirname}output/${nowProject.id}/router/routerConfig.json`,'utf8');
    let useResult = eval('(' + result + ')');
    if(JSON.stringify(nowRightClickItem) == '{}'){
        //空白
        useResult.push(params);
    }else if(typeof nowRightClickItem.name != 'undefined'){
        //节点
        //节点点击：新增页面
        //删除原节点下的json文件
        await fs.removeSync(`${window.preload.dirname}output/${nowProject.id}/json/${nowRightClickItem.name}.json`);
        //将此节点改换为章节
        const changeItem = await changeRouteObj(nowRightClickItem);
        changeItem.secMenu.push(params);
        //更换json信息
        //将树形结构转化为数组
        let treeToArrayArr = treeToArray(useResult);
        //找到此节点在数组中的位置
        let infoPosition = array_getObjPosition(treeToArrayArr,changeItem);
        //设置json信息的父路径
        if(typeof treeToArrayArr[infoPosition].fatherPath != 'undefined'){
            changeItem.fatherPath = treeToArrayArr[infoPosition].fatherPath;
        }
        //替换数组中的此信息
        treeToArrayArr.splice(infoPosition,1,changeItem);
        //3.添加路由JSON信息数据，将数组转化为树形结构
        useResult = arrayToTree(treeToArrayArr);
    }else{
        //将树形结构转化为数组
        let treeToArrayArr = treeToArray(useResult);
        //将新建节点添加父节点，并添加
        params.fatherPath = nowRightClickItem.path;
        treeToArrayArr.push(params);
        //将数组转化为树形结构
        useResult = arrayToTree(treeToArrayArr);
    }
    return useResult;
}

//删除页面
async function deleteRouteConfig(nowRightClickItem){
    let nowProject = getProject();
    const result = await fs.readFile(`${window.preload.dirname}output/${nowProject.id}/router/routerConfig.json`,'utf8');
    let useResult = eval('(' + result + ')');
    if(typeof nowRightClickItem.name != 'undefined'){
        //将树形结构转化为数组
        let treeToArrayArr = treeToArray(useResult);
        //找到此节点在数组中的位置
        let infoPosition = array_getObjPosition(treeToArrayArr,nowRightClickItem);
        //删除数组中的此信息
        let nowArrInItem = treeToArrayArr[infoPosition];
        if(typeof nowArrInItem.fatherPath != 'undefined'){
            //有父亲节点：判断是否有兄弟节点
            console.log('array_nodeNum',array_nodeNum(treeToArrayArr,nowArrInItem));
            if(array_nodeNum(treeToArrayArr,nowArrInItem) >= 2){
                //有兄弟节点
                treeToArrayArr.splice(infoPosition,1);
            }else{
                //无兄弟节点：删除此节点，并且将父节点从章节转为为节点：
                let fatherItem = arr_findItem(treeToArrayArr,nowArrInItem.fatherPath);
                //将父节点从章节转为为节点
                let newFatherItem = nodeToItemObj(fatherItem);
                newFatherItem.fatherPath = fatherItem.fatherPath;
                //删除此节点
                treeToArrayArr.splice(infoPosition,1);
                //删除原节点下的json文件
                await fs.removeSync(`${window.preload.dirname}output/${nowProject.id}/json/${nowRightClickItem.name}.json`);
                //删除预览下的.vue文件
                await fs.removeSync(`${window.preload.dirname}output/${nowProject.id}/preview/${nowRightClickItem.name}.vue`);
                //找到此父节点位置，并进行替换
                let infoFatherPosition = array_getObjPosition(treeToArrayArr,fatherItem);
                treeToArrayArr.splice(infoFatherPosition,1,newFatherItem);
                //创建json文件
                await createNativeFile(newFatherItem.name);
            }
        }else{
            //无父亲节点
            treeToArrayArr.splice(infoPosition,1);
        }
        //3.添加路由JSON信息数据，将数组转化为树形结构
        useResult = arrayToTree(treeToArrayArr);
        //删除当前页面json文件
        await fs.removeSync(`${window.preload.dirname}output/${nowProject.id}/json/${nowRightClickItem.name}.json`);
        //删除预览下的.vue文件
        await fs.removeSync(`${window.preload.dirname}output/${nowProject.id}/preview/${nowRightClickItem.name}.vue`);
    }else{
        //章节点击：删除全部章节
        //将树形结构转化为数组
        let treeToArrayArr = treeToArray(useResult);
        //找到此节点在数组中的位置
        let infoPosition = array_getObjPosition(treeToArrayArr,nowRightClickItem);
        let nowArrInItem = treeToArrayArr[infoPosition];
        if(typeof nowArrInItem.fatherPath != 'undefined'){
            //有父亲节点，获取所有子节点
            let allChildNode = getAllChild(useResult,nowArrInItem.path,[]);
            //将本身节点加入到数组中
            allChildNode.push({path:nowArrInItem.path})
            //将所有子节点删除
            let saveArr = array_deleteAllItem(allChildNode,treeToArrayArr);
            //删除文件
            allChildNode.forEach(async (item) => {
                if(typeof item.name != "undefined"){
                    await fs.removeSync(`${window.preload.dirname}output/${nowProject.id}/json/${item.name}.json`);
                    //删除预览下的.vue文件
                    await fs.removeSync(`${window.preload.dirname}output/${nowProject.id}/preview/${nowRightClickItem.name}.vue`);
                }
            })
            //有父亲节点：判断是否有兄弟节点
            console.log('array_nodeNum',array_nodeNum(treeToArrayArr,nowArrInItem));
            if(array_nodeNum(treeToArrayArr,nowArrInItem) < 2){
                //无兄弟节点，将父章节转化为节点
                let fatherItem = arr_findItem(treeToArrayArr,nowArrInItem.fatherPath);
                let newFatherItem = nodeToItemObj(fatherItem);
                newFatherItem.fatherPath = fatherItem.fatherPath;
                //找到此父节点位置，并进行替换
                let infoFatherPosition = array_getObjPosition(saveArr,fatherItem);
                saveArr.splice(infoFatherPosition,1,newFatherItem);
                //创建json文件
                await createNativeFile(newFatherItem.name);
            }
            //3.添加路由JSON信息数据，将数组转化为树形结构
            useResult = arrayToTree(JSON.parse(JSON.stringify(saveArr)));
        }else{
            //无父亲节点
            let chapterIndex = array_getObjPosition(useResult,nowRightClickItem);
            let awaitDeleteArr = [];
            awaitDeleteArr.push(useResult[chapterIndex]);
            //删除树形结构中的数据
            useResult.splice(chapterIndex,1)
            //将树形结构转化为数组
            let deleteTreeToArrayArr = treeToArray(awaitDeleteArr);
            console.log('deleteTreeToArrayArr',deleteTreeToArrayArr)
            deleteTreeToArrayArr.forEach(async (item) => {
                await fs.removeSync(`${window.preload.dirname}output/${nowProject.id}/json/${item.name}.json`);
                //删除预览下的.vue文件
                await fs.removeSync(`${window.preload.dirname}output/${nowProject.id}/preview/${nowRightClickItem.name}.vue`);
            })
        }
    }
    return useResult;
}



function createRouteObj(params){
    var createParams = {
        "name":params.name,
        "path":`/${params.path}`,
        "component":`() => import('@/view/${params.name}/index.vue')`,
        "meta":{
            "title":params.sideBarName
        },
        "sideBarIconName":"present",
        "sideBarName":params.sideBarName,
        "sideBarShow":true,
        "auth":"admin",
        "homePage":true,
        "children":[]
    }
    return createParams;
}

function changeRouteObj(item){
    var params = {
        "path":item.path,
        "meta": {
            "title": item.meta.title
        },
        "sideBarIconName": "location",
        "sideBarName": item.sideBarName,
        "sideBarShow": item.sideBarShow,
        "auth": item.auth,
        "secMenu":[]
    }
    return params;
}

function nodeToItemObj(item){
    if(item.path.split("/").length == 2){
        var componentValue = `() => import('@/view${item.path}/index.vue')`
    }else{
        var componentValue = `() => import('@/view${item.path}.vue')`
    }
    var createParams = {
        "name":item.path,
        "path":item.path,
        "component":componentValue,
        "meta":{
            "title":item.meta.title
        },
        "sideBarIconName":"present",
        "sideBarName":item.sideBarName,
        "sideBarShow":true,
        "auth":"admin",
        "homePage":true,
        "children":[]
    }
    return createParams;
}

async function rewriteRouteConfig(params){
    let nowProject = getProject();
    await fs.writeJsonSync(`${window.preload.dirname}output/${nowProject.id}/router/routerConfig.json`, params)
}

export{
    formatRouteConfig,
    deleteRouteConfig,
    rewriteRouteConfig,
    createRouteObj,
    changeRouteObj,
    nodeToItemObj
}